package com.yrxy.thread.case14;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class PaymentService {

    /**
     * 异步支付的入口方法
     *
     * @return
     */
    public static boolean asyncPay() {
        //校验
        CompletableFuture<Boolean> isValid = CompletableFuture.supplyAsync(() -> CheckService.isValid());
        //创建订单
        CompletableFuture<Integer> orderSum = CompletableFuture.supplyAsync(() -> OrderService.createOrder());
        //支付
        CompletableFuture<Integer> money = CompletableFuture.supplyAsync(() -> basePay());

        // 上面三个都完成之后,再进行下面匿名内部类的代码
        CompletableFuture.allOf(isValid, orderSum, money)
                .thenRun(() -> System.out.println("完成异步支付"))
                .join();

        return true;

    }

    /**
     * 同步支付的入口方法
     *
     * @return
     */
    public static boolean syncPay() {
        CheckService.isValid();
        OrderService.createOrder();
        basePay();
        System.out.println("同步支付成功");

        //假设支付成功
        return true;
    }

    public static int basePay() {
        int money = 1000;
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("支付");
        //假设支付成功
        return money;
    }

}
